//
//  StatusListViewModel.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/10.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import Foundation
import SDWebImage

class StatusListViewModel {
    //微博数据数组
    lazy var statusList = [StatusVewModel]()
    //下拉刷新条数
    var pulldownCount: Int?
    ///加载数据
    func loadData(isPullup isPullup: Bool, finished:(isSucceed: Bool) -> ()) {
        
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) - 1 : 0
        
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id, finished: { (result, error) -> () in
            if error != nil {
                print("Home加载数据出错了")
                finished(isSucceed: false)
                return
            }
            
            guard let array  = result?["statuses"] as? [[String: AnyObject]] else{
                print("数据格式错误")
                finished(isSucceed: false)
                return
            }
            
            var dataList = [StatusVewModel]()
            
            for dict in array {
                dataList.append(StatusVewModel(status: Status(dict: dict)))
            }
            
            //下拉刷新数据
            self.pulldownCount = since_id > 0 ? dataList.count : nil
            
            //拼接数据
            if max_id > 0 {
                self.statusList = self.statusList + dataList
            }else {
                self.statusList = dataList + self.statusList
            }
           print("取到了 \(dataList.count) 数据")
            
            self.cacheSingleImage(dataList,finished: finished)
            
        })
    }
    ///缓存单张图片
    func cacheSingleImage(dataList: [StatusVewModel], finished:(isSucceed: Bool) -> ()) {
        
        let group = dispatch_group_create()
        
        var dataLength = 0
        
        for vm in dataList {
            
            if vm.thumbnail?.count != 1 {
                continue
            }
            
            let url = vm.thumbnail![0]
            
            dispatch_group_enter(group)

            SDWebImageManager.sharedManager().downloadImageWithURL(url,
                options: [],
                progress: nil, completed: { (image, _, _, _, _) -> Void in
                
                    if let img = image, let data = UIImagePNGRepresentation(img) {
                        
                        dataLength += data.length
                    }
                    dispatch_group_leave(group)
                    
            })
            
            
            
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
//            print("缓存完成，大小: \(dataLength / 1024) B")
            finished(isSucceed: true)
        })
    }
}